﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Patterns.UnitOfWorkPattern.EF
{
    public class EfFactory
    {
        public static void RegisteryContexts(params Type[] contextTypes)
        {
        }

        public System.Data.Entity.DbSet<TEntity> GetDbSetForUoW<TEntity>(IMultiContextUnitOfWork uow) where TEntity : class
        {
            Type contextType;
            Type entityBaseType;

            if (!TypeLookUp.IsTypeCompatible(typeof(TEntity), out contextType, out entityBaseType))
                return null;

            var context = uow.GetContext(contextType) as EfContext;

            var set = context.Set(entityBaseType) as System.Data.Entity.DbSet<TEntity>;

            return set;
        }

        public static System.Data.Entity.DbSet<TEntity> GetDbSetWithoutUoW<TEntity>() where TEntity : class
        {
            Type contextType;
            Type entityBaseType;

            if (!TypeLookUp.IsTypeCompatible(typeof(TEntity), out contextType, out entityBaseType))
                return null;

            var contextConstructor = contextType.GetConstructor(new Type[] { });

            if (contextConstructor == null)
                return null;

            var context = contextConstructor.Invoke(new object[] { }) as EfContext;

            var set = context.Set(entityBaseType) as System.Data.Entity.DbSet<TEntity>;

            return set;
        }
    }
}
